﻿using System;
using Client.Interfaces;
using Global.Interfaces.Server;
using System.Collections.Generic;
using Global.Impl.Server;
using System.Threading;
using Client.secureMessengerServer;
using System.IO;
using System.Reflection;
using Interfaces.Impl;

namespace Client.Controllers
{
    internal class BuddyListController : IBuddyListController
    {
        #region Variables
        private IMainController _mainController;
        private IBuddyListView _view;
        private IsMessengerServerClient _sMessengerServer;
        private Thread _thread;
        private bool _shouldThreadRun;
        private readonly object sharedObject = new object();
        #endregion

        internal BuddyListController(IMainController mainController, IBuddyListView view)
        {
            _mainController = mainController;
            _view = view;

            _shouldThreadRun = true;
            _thread = new Thread(new ThreadStart(GetUsersAndChats)); 
            _thread.SetApartmentState(ApartmentState.STA);
            _thread.Start();
        }

        #region Getting users and chats
        private void GetUsersAndChats()
        {
            _sMessengerServer = new IsMessengerServerClient("secureMessengerServerEndpoint");

            _sMessengerServer.ClientCredentials.ClientCertificate.Certificate = Certificate.CertificateLoader.GetClientCertificate(_mainController.Password);

            while (ShouldThreadRun)
            {
                GetUsersFromServer();
                GetChatsFromServer();

                try
                {
                    Thread.Sleep(5000);
                }
                catch (Exception) { }
            }
        }

        #region Get chat
        private void GetChatsFromServer()
        {
            _sMessengerServer.BeginGetChatList(_mainController.Username, GetChatsEnded, null);
        }

        private void GetChatsEnded(IAsyncResult result)
        {
            List<ChatRequest> chats = _sMessengerServer.EndGetChatList(result);
            foreach (ChatRequest request in chats)
                _mainController.CreateChatSession(request);
        }
        #endregion

        #region Get users
        private void GetUsersFromServer()
        {
            _sMessengerServer.BeginGetBuddyList(_mainController.Username, GetUsersEnded, null);
        }

        private void GetUsersEnded(IAsyncResult result)
        {
            try
            {
                List<Buddy> buddies = _sMessengerServer.EndGetBuddyList(result);
                _view.ClearBuddyList();
                foreach (IBuddy b in buddies)
                    _view.AddBuddyToList(b);
            }
            catch (Exception)
            {
            }
        }
        #endregion
        #endregion

        #region IBuddyListC Members

        public bool ShouldThreadRun
        {
            get
            {
                bool tmp;
                lock (sharedObject)
                {
                    tmp = _shouldThreadRun;
                }
                return tmp;
            }
            set
            {
                lock (sharedObject)
                {
                    _shouldThreadRun = value;
                }
            }
        }

        public void StartChat(IBuddy buddy)
        {
            Guid guid = Guid.NewGuid();
            string password = RandomPassword.Generate(30);
            ChatWindow chatWindow = new ChatWindow(_mainController, guid.ToString(), password, buddy);
            chatWindow.Show();
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            ShouldThreadRun = false;
            _thread.Interrupt();
        }

        #endregion
    }
}
